const { User, Resource, KnowledgePoint } = require('../models');
const cozeClient = require('../utils/cozeClient');
const eduSystemClient = require('../utils/eduSystemClient');

/**
 * 生成个性化定制资源
 * @route POST /api/custom/generate
 */
const generateCustomResource = async (req, res, next) => {
  try {
    const { courseOutlineId, weakKnowledgeIds, userId = 1 } = req.body;
    
    // 1. 获取用户信息
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '用户不存在'
      });
    }
    
    // 2. 获取课程大纲
    const courseOutline = await eduSystemClient.getCourseOutline(courseOutlineId);
    
    // 3. 获取薄弱知识点详情
    const weakKnowledgePoints = [];
    for (const knowledgePointId of weakKnowledgeIds) {
      const detail = await eduSystemClient.getKnowledgePointDetail(knowledgePointId);
      weakKnowledgePoints.push(detail);
    }
    
    // 4. 构建Coze智能体输入参数
    const customParams = {
      courseOutline: {
        id: courseOutlineId,
        name: courseOutline.courseName,
        description: courseOutline.description
      },
      weakKnowledgePoints: weakKnowledgePoints.map(kp => ({
        id: kp.id,
        name: kp.name,
        description: kp.description,
        difficulty: kp.difficulty,
        importance: kp.importance
      })),
      userPreference: user.stylePreference || {},
      outputFormat: 'JSON' // 请求结构化输出
    };
    
    // 5. 调用Coze智能体生成个性化定制资源
    const customResult = await cozeClient.callBot('customBot', customParams);
    
    // 6. 保存生成的资源到资源表
    const resources = [];
    
    // 6.1 保存教学设计资源
    if (customResult.design) {
      const designResource = await Resource.create({
        userId,
        type: 'design',
        content: customResult.design,
        isSaved: false
      });
      resources.push({
        type: 'design',
        resourceId: designResource.id,
        content: customResult.design
      });
    }
    
    // 6.2 保存练习题资源
    if (customResult.exercises) {
      const exerciseResource = await Resource.create({
        userId,
        type: 'exercise',
        content: customResult.exercises,
        isSaved: false
      });
      resources.push({
        type: 'exercise',
        resourceId: exerciseResource.id,
        content: customResult.exercises
      });
    }
    
    // 6.3 保存多媒体资源
    if (customResult.media) {
      const mediaResource = await Resource.create({
        userId,
        type: 'media',
        content: customResult.media,
        isSaved: false
      });
      resources.push({
        type: 'media',
        resourceId: mediaResource.id,
        content: customResult.media
      });
    }
    
    // 7. 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        customResources: resources,
        weakKnowledgePoints: weakKnowledgePoints.map(kp => kp.name),
        courseOutline: courseOutline.courseName
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取个性化定制资源详情
 * @route GET /api/custom/:resourceId
 */
const getCustomResourceDetail = async (req, res, next) => {
  try {
    const { resourceId } = req.params;
    
    // 查询资源
    const resource = await Resource.findByPk(resourceId);
    
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '资源不存在'
      });
    }
    
    // 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        resourceId: resource.id,
        userId: resource.userId,
        type: resource.type,
        content: resource.content,
        generateTime: resource.generateTime,
        isSaved: resource.isSaved
      }
    });
  } catch (error) {
    next(error);
  }
};

module.exports = {
  generateCustomResource,
  getCustomResourceDetail
};